<template>
  <div class="edit-page-wrap">
    <Head title="基础信息">
      <template #content>
        <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item label="标签名称" prop="labelName">
            <el-input
              v-model.trim="ruleForm.labelName"
              placeholder="请输入标签名称"
              maxlength="30"
              clearable
            />
          </el-form-item>
          <el-form-item
            v-if="orgType === 'CHANNEL'"
            label="标签类型"
            prop="type"
            class="has-tips"
          >
            <el-radio-group
              v-model="ruleForm.type"
              v-for="(item, index) in optionsS.labelType"
              :key="index"
              @change="handleLabelType"
              :disabled="Boolean(id)"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
            <div class="tip">
              <div class="icon"></div>
              {{
                ruleForm.type === '0'
                  ? '数据标签：将选择的数据对象绑定一起并进行命名，可在营销活动中直接应用。'
                  : '推荐站点标签：标签绑定的电站会在移动端推荐展示，优先级越低展示越靠前。'
              }}
            </div>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type === '0'"
            label="移动端可见"
            prop="isVisible"
          >
            <el-radio-group
              v-model="ruleForm.isVisible"
              v-for="(item, index) in optionsS.isVisible"
              :key="index"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            v-if="ruleForm.type === '1'"
            label="优先级"
            prop="stationPriority"
          >
            <el-input
              v-model.trim="ruleForm.stationPriority"
              placeholder="请输入正整数"
              maxlength="9"
              clearable
            />
          </el-form-item>
        </el-form>
      </template>
    </Head>
    <Head title="数据选择">
      <template #content>
        <el-form
          ref="ruleFormRef1"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="edit-form-wrap"
        >
          <el-form-item
            v-if="orgType === 'CHANNEL' && ruleForm.type === '0'"
            label="数据类型"
            prop="dataType"
            @change="handleLabelType"
          >
            <el-radio-group
              v-model="ruleForm.dataType"
              v-for="(item, index) in optionsS.dataType"
              :key="index"
              :disabled="Boolean(id)"
            >
              <el-radio :label="item.value">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div class="select-wrap">
          <div class="left">已选择</div>
          <div class="right">
            <el-scrollbar>
              <div class="item-wrap">
                <div
                  class="item"
                  v-for="(item, index) in data.selectArr"
                  :key="index"
                >
                  {{ item.name
                  }}<el-icon @click="cliceIcon(item, index)"><Close /></el-icon>
                </div>
              </div>
            </el-scrollbar>
          </div>
        </div>
        <div class="edit-wrap">
          <div
            class="table-title"
            v-if="ruleForm.type === '0' && ruleForm.dataType === '0'"
          >
            请选择用户
          </div>
          <div
            class="table-title"
            v-if="
              (ruleForm.type === '0' && ruleForm.dataType === '1') ||
              ruleForm.type === '1'
            "
          >
            请选择电站
          </div>
          <Table
            v-if="ruleForm.type === '0' && ruleForm.dataType === '0'"
            ref="tableUserRef"
            :columns="data.columns1"
            :toolbar="data.toolbar"
            :query="data.query1"
            :select="true"
            @get-list="getDataUser"
          ></Table>
          <Table
            v-if="
              (ruleForm.type === '0' && ruleForm.dataType === '1') ||
              ruleForm.type === '1'
            "
            ref="tableStationRef"
            :columns="data.columns2"
            :toolbar="data.toolbar"
            :query="data.query2"
            :select="true"
            @get-list="getDataStation"
          ></Table>
        </div>
      </template>
    </Head>
    <div class="edit-btn-wrap">
      <el-button type="primary" plain @click="back">取消</el-button>
      <el-button type="primary" v-btnAntiShake="onSubmit">保存</el-button>
    </div>
  </div>
</template>

<script lang="ts" setup>
import Head from '@/components/head/index.vue';
import Table from '@/components/table/index.vue';
import { FormInstance, FormRules } from 'element-plus';
import { queryDicByParent } from '@/service/apis/api';
import {
  queryUserList,
  queryLabelStationList,
  addLabel,
  updateLabel,
  queryLabelDetail,
} from '@/service/apis/market';
import { getRegion } from '@/utils/utils';
import {
  USER_TYPE,
  USER_TYPES,
  STATION_STATUS_USE,
} from '@/utils/dictionaries';
import { IS_INT } from '@/utils/verify';

const router = useRouter();
const route = useRoute();
const {
  query: { id },
} = route;

const ruleFormRef = ref<FormInstance>();
const ruleFormRef1 = ref<FormInstance>();
const tableUserRef = ref();
const tableStationRef = ref();

const orgType = window.localStorage.getItem('orgType');

const optionsS = reactive({
  labelType: [] as any,
  dataType: [] as any,
  isVisible: [] as any,
});

// 字典
queryDicByParent({
  listDtos: ['labelType', 'dataType', 'isVisible'],
}).then((res: any) => {
  optionsS.labelType = res.labelType;
  optionsS.dataType = res.dataType;
  optionsS.isVisible = res.isVisible;
});

// 获取省市区
getRegion().then((res: any) => {
  data.query2[2].props.options = [...res];
});

if (id) {
  queryLabelDetail({ id: id }).then((res: any) => {
    for (const key in ruleForm) {
      if (res[key]) {
        ruleForm[key] = res[key];
      }
    }
    if (ruleForm.type === '0' && ruleForm.dataType === '0') {
      // 用户
      data.selectArr = res.userList1.map((item: any) => ({
        id: item.id,
        name: item.accountNumber,
      }));
    } else if (
      (ruleForm.type === '0' && ruleForm.dataType === '1') ||
      ruleForm.type === '1'
    ) {
      // 电站
      data.selectArr = res.stationList.map((item: any) => ({
        id: item.value,
        name: item.label,
      }));
    }
  });
}

const ruleForm: any = reactive({
  labelName: '', // 标签名称
  type: '0', // 标签类型
  isVisible: '0', // 移动端可见
  stationPriority: '', //优先级
  dataType: '0', // 数据类型
});

if (orgType !== 'CHANNEL') {
  ruleForm.dataType = orgType === '0' ? '1' : '0';
}

const rules = reactive<FormRules>({
  labelName: [{ required: true, message: '请输入标签名称', trigger: 'blur' }],
  type: [
    { required: true, message: '请选择标签类型', trigger: ['blur', 'change'] },
  ],
  isVisible: [
    {
      required: true,
      message: '请选择移动端是否可见',
      trigger: ['blur', 'change'],
    },
  ],
  stationPriority: [
    { required: true, message: '请输入优先级', trigger: 'blur' },
    {
      pattern: IS_INT,
      message: '请输入正确的优先级，正整数',
      trigger: 'blur',
    },
  ],
  dataType: [
    { required: true, message: '请选择数据类型', trigger: ['blur', 'change'] },
  ],
});

const data = reactive({
  list: [] as any,
  selectArr: [] as any,
  columns1: [
    {
      prop: 'orgName',
      label: '归属企业',
    },
    {
      prop: 'accountNumber',
      label: '用户账号',
    },
    {
      prop: 'userName',
      label: '用户姓名',
    },
    {
      prop: 'plateNumber',
      label: '车牌号',
    },
    {
      prop: 'unit',
      label: '用户类型',
      dic: USER_TYPES,
    },
    {
      prop: 'mobile',
      label: '手机号',
    },
    {
      prop: 'isFrozen',
      label: '状态',
      dic: USER_TYPE,
    },
    {
      prop: 'createTime',
      label: '注册时间',
    },
  ],
  columns2: [
    {
      prop: 'stationName',
      label: '充电站名称',
    },
    {
      prop: 'address',
      label: '充电站地址',
      // template: (row: any, index: number) => {
      //   return `${row.areaCodeName}${row.address}` || '--';
      // },
    },
    {
      prop: 'operatorName',
      label: '运营商',
    },
    {
      prop: 'areaCodeName',
      label: '区划',
    },
    {
      prop: 'chargeTimes',
      label: '充电次数',
      template: (row: any, index: number) => {
        return row.chargeTimes || '0';
      },
    },
    {
      prop: 'isEnableStart',
      label: '启停状态',
      dic: STATION_STATUS_USE,
      type: Boolean,
    },
  ],
  query1: [
    {
      label: '归属企业',
      prop: 'orgName',
      comName: 'input',
      props: {
        placeholder: '请输入归属企业',
      },
    },
    {
      label: '用户账号',
      prop: 'accountNumber',
      comName: 'input',
      props: {
        placeholder: '请输入用户账号',
      },
    },
    {
      label: '用户姓名',
      prop: 'userName',
      comName: 'input',
      props: {
        placeholder: '请输入用户姓名',
      },
    },
    {
      label: '用户类型',
      prop: 'unit',
      comName: 'select',
      props: {
        placeholder: '请选择用户类型',
        change: (value: any) => {
          console.log(value);
        },
        options: USER_TYPES,
      },
    },
    {
      label: '手机号',
      prop: 'mobile',
      comName: 'input',
      props: {
        placeholder: '请输入手机号',
      },
    },
    // {
    //   label: '车牌号',
    //   prop: 'plateNumber',
    //   comName: 'input',
    //   props: {
    //     placeholder: '请输入车牌号',
    //   },
    // },
    {
      label: '用户状态',
      prop: 'isFrozen',
      comName: 'select',
      props: {
        placeholder: '请选择用户状态',
        change: (value: any) => {
          console.log(value);
        },
        options: USER_TYPE,
      },
    },
    {
      label: '注册时间',
      prop: 'time',
      comName: 'date',
      keys: ['startTime', 'endTime'],
      props: {
        type: 'daterange',
      },
    },
  ],
  query2: [
    {
      label: '电站名称',
      prop: 'stationName',
      comName: 'input',
      props: {
        placeholder: '请输入电站名称',
      },
    },
    {
      label: '归属运营商',
      prop: 'operatorName',
      comName: 'input',
      props: {
        placeholder: '请输入归属运营商',
      },
    },
    {
      label: '区划',
      prop: 'regions',
      comName: 'cascader',
      props: {
        placeholder: '请选择区划',
        options: [] as any,
        props: {
          checkStrictly: true,
        },
      },
    },
  ],
  toolbar: [
    {
      label: '添加',
      type: 'primary',
      handle: (row: any) => {
        addData(row);
      },
    },
    {
      label: '移除',
      type: 'primary',
      handle: (row: any) => {
        removeData(row);
      },
    },
  ],
});

// 添加
const addData = (row: any) => {
  if (ruleForm.type === '0' && ruleForm.dataType === '0') {
    // 用户
    const arr = tableUserRef.value?.getSelectData();
    if (arr.length === 0) {
      ElMessageBox.alert(`请勾选需要添加的用户`, '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return;
    }
    arr.forEach((item: any) => {
      const temp = data.selectArr.find((it: any) => it.id === item.id);
      if (!temp) {
        data.selectArr.push({
          name: item.accountNumber,
          id: item.id,
        });
      }
    });
    tableUserRef.value?.clearSelect();
  } else if (
    (ruleForm.type === '0' && ruleForm.dataType === '1') ||
    ruleForm.type === '1'
  ) {
    // 电站
    const arr = tableStationRef.value?.getSelectData();
    if (arr.length === 0) {
      ElMessageBox.alert(`请勾选需要添加的电站`, '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return;
    }
    arr.forEach((item: any) => {
      const temp = data.selectArr.find((it: any) => it.id === item.id);
      if (!temp) {
        data.selectArr.push({
          name: item.stationName,
          id: item.id,
        });
      }
    });
    tableStationRef.value?.clearSelect();
  }
};
// 移除
const removeData = (row: any) => {
  if (ruleForm.type === '0' && ruleForm.dataType === '0') {
    // 用户
    const arr = tableUserRef.value?.getSelectData();
    if (arr.length === 0) {
      ElMessageBox.alert(`请勾选需要移除的用户`, '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return;
    }
    const arr1: any = [];
    data.selectArr.forEach((item: any) => {
      const temp = arr.find((it: any) => it.id === item.id);
      if (!temp) {
        arr1.push(item);
      }
    });
    data.selectArr = arr1;
    tableUserRef.value?.clearSelect();
  } else if (
    (ruleForm.type === '0' && ruleForm.dataType === '1') ||
    ruleForm.type === '1'
  ) {
    // 电站
    const arr = tableStationRef.value?.getSelectData();
    if (arr.length === 0) {
      ElMessageBox.alert(`请勾选需要移除的电站`, '提示', {
        confirmButtonText: '确认',
        type: 'warning',
      });
      return;
    }
    const arr1: any = [];
    data.selectArr.forEach((item: any) => {
      const temp = arr.find((it: any) => it.id === item.id);
      if (!temp) {
        arr1.push(item);
      }
    });
    data.selectArr = arr1;
    tableStationRef.value?.clearSelect();
  }
};

const cliceIcon = (item: any, index: number) => {
  data.selectArr.splice(index, 1);
};

const handleLabelType = () => {
  data.selectArr = [];
};

const getDataUser = (page: any, search: any) => {
  const form = { ...search.ruleForm };
  if (form.time?.length > 0) {
    form.startTime = form.time[0];
    form.endTime = form.time[1];
    delete form.time;
  }
  queryUserList(form, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getDataUser(page, search);
        return;
      }
      data.list = [...res.list];
      nextTick(() => {
        tableUserRef.value?.setTable({
          total: res.total,
          table: data.list,
        });
      });
    }
  });
};

const getDataStation = (page: any, search: any) => {
  const form = search.ruleForm;
  delete form.provinceCode;
  delete form.cityCode;
  delete form.areaCode;
  if (form.regions?.length === 1) {
    form.provinceCode = form.regions[0];
  }
  if (form.regions?.length === 2) {
    form.provinceCode = form.regions[0];
    form.cityCode = form.regions[1];
  }
  if (form.regions?.length === 3) {
    form.provinceCode = form.regions[0];
    form.cityCode = form.regions[1];
    form.areaCode = form.regions[2];
  }
  queryLabelStationList(form, page).then((res: any) => {
    if (res) {
      if (page.pageNo !== 1 && (!res.dataList || res.dataList?.length === 0)) {
        page.pageNo--;
        getDataStation(page, search);
        return;
      }
      data.list = [...res.dataList];
      nextTick(() => {
        tableStationRef.value?.setTable({
          total: res.totalCount,
          table: data.list,
        });
      });
    }
  });
};

const back = () => {
  router.go(-1);
};

const emit = defineEmits(['clear-cache']);
const onSubmit = async () => {
  if (!ruleFormRef.value || !ruleFormRef1.value) return;
  let flag = true;
  let objError = {} as any;
  await Promise.all([
    ruleFormRef.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
    ruleFormRef1.value.validate((e: any, fields: any) => {
      flag = flag ? e : false;
      if (!e) {
        objError = { ...objError, ...fields };
      }
    }),
  ]);
  if (!flag) {
    for (const key in ruleForm) {
      if (objError[key]) {
        ruleFormRef.value.scrollToField(key);
        ruleFormRef1.value.scrollToField(key);
        break;
      }
    }
    return;
  }
  if (data.selectArr?.length === 0) {
    ElMessage({
      showClose: true,
      message: '请选择用户或电站数据',
      type: 'warning',
    });
    return;
  }
  const form: any = {
    labelName: ruleForm.labelName,
    type: ruleForm.type,
  };
  if (ruleForm.type === '0') {
    form.isVisible = ruleForm.isVisible;
    form.dataType = ruleForm.dataType;
  } else {
    form.stationPriority = ruleForm.stationPriority;
  }
  form.userDTOList = [];
  data.selectArr.forEach((item: any) => {
    form.userDTOList.push(item.id);
  });
  if (id) {
    form.id = id;
    updateLabel(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  } else {
    addLabel(form).then((res: any) => {
      emit('clear-cache');
      back();
    });
  }
};
</script>

<style lang="scss" scoped>
.select-wrap {
  display: flex;
  width: calc(100% - 40px);
  min-height: 112px;
  max-height: 200px;
  margin: 0 20px 20px 20px;
  padding: 8px 0;
  border: 1px solid #c4c4c4;
  border-radius: 8px;
  font-size: 12px;

  .left {
    line-height: 20px;
    margin: 16px 20px;
    color: #242424;
    font-weight: bold;
  }
  .right {
    display: flex;
    flex-wrap: wrap;
    width: calc(100% - 76px);
    max-height: 200px;
    color: var(--el-color-primary);

    .item-wrap {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      max-height: 200px;
    }

    .item {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 32px;
      padding: 0 7px;
      margin: 8px 20px 8px 0;
      background-color: #f6f8ff;
      border: 1px solid var(--el-color-primary);
      border-radius: 8px;
    }
    .el-icon {
      padding-left: 6px;
      cursor: pointer;
    }
  }
}

.edit-wrap {
  .table-title {
    margin: 10px 17px;
    line-height: 20px;
    font-size: 12px;
    color: #242424;
    font-weight: bold;
  }
}
</style>